import scope from "@patarapolw/scope-css";
import fetchajaxgettext from "./fetchajaxgettext.cjs";
import { getscopeidofurl } from "./getscopeofurl";
import styletexttocssrulesstrings from "./styletexttocssrulesstrings.cjs";

export async function scopestylesheet(
    stylecssrules: Set<string>,
    tmpcontainer: HTMLElement,
    url: string
    // dependencies: Set<string>
) {
    // const { cachestylecssrules } = states;

    // const stylecssrules =
    //     cachestylecssrules.get(url) || reactive(new Set<string>());
    // cachestylecssrules.get(url) || cachestylecssrules.set(url, stylecssrules);
    await Promise.all(
        Array.from(tmpcontainer.querySelectorAll("link")).map(async (link) => {
            if (link.rel !== "stylesheet") {
                link.remove();
                return;
            }
            // console.log(link);
            const rawhref = link.getAttribute("href");
            if (!rawhref) {
                link.remove();
                return;
            }
            const linkhref = String(new URL(rawhref, url));
            const stylesheetcontent = await fetchajaxgettext(linkhref);
            // dependencies.add(linkhref);
            if (link.hasAttribute("global")) {
                const rawstyletext = stylesheetcontent;
                styletexttocssrulesstrings(rawstyletext).forEach((s) => {
                    stylecssrules.add(s);
                });

                link.remove();
                return;
            } else {
                // console.log(link);
                //link to style
                link.remove();

                const style = document.createElement("style");

                style.textContent = stylesheetcontent;
                tmpcontainer.appendChild(style);
                return;
            }
        })
    );
    Array.from(tmpcontainer.querySelectorAll("style")).forEach((style) => {
        console.log(style);
        if (style.hasAttribute("global")) {
            const rawstyletext = style.textContent || "";
            styletexttocssrulesstrings(rawstyletext).forEach((s) => {
                stylecssrules.add(s);
            });

            style.remove();
            style.parentNode?.removeChild(style);
            return;
        } else {
            const rawstyletext = scope(
                style.textContent || "",
                "." + getscopeidofurl(url)
            );
            styletexttocssrulesstrings(rawstyletext).forEach((s) => {
                stylecssrules.add(s);
            });
            // console.log(style);
            // console.log(style.parentNode);
            style.remove();

            style.parentNode?.removeChild(style);
            return;
        }
    });
}
